# -*- coding: utf-8 -*-
from flask import Flask
from flask import request
import sys
import os
import urllib
import urllib2
from matlab import engine
import time
import random
import config
import hashlib

app = Flask(__name__)


def mkdir(paths):
    rootpath = ""
    for path in paths:
        rootpath = rootpath + path
        if os.path.exists(rootpath) == False:
            os.mkdir(rootpath)
        rootpath = rootpath + "/"


@app.route("/", methods=["POST", "GET"])
def root():
    return "root"

@app.route('/git', methods=["POST", "GET"])
def gitpull():
    os.system('git pull')
    return "success";

@app.route('/clearlog', methods=["GET"])
def clearlog():
    pathlogfile = "static/mq.log"
    f = open(pathlogfile, "r+")
    f.truncate()
    return "success"


@app.route("/match", methods=["POST", "GET"])
def match():
    """
    计算比赛，一个请求，返回一个计算key,这样可以使得不同的客户端都能够在本系统进行计算
    :return:
    """
    # 下载文件
    callbackurl = request.form['callbackurl']
    client = request.form['client']
    id = request.form['id']
    anglel = request.form['anglel']
    angler = request.form['angler']
    sensorl = request.form['sensorl']
    sensorr = request.form['sensorr']
    gps = request.form['gpsl']
    court = request.form['court']
    files = [anglel, angler, sensorl, sensorr, gps, court]

    rootpath = os.getcwd()
    matchdir = "static/match/" + client + "/" + id
    mkdir(["static", "match", client, id])

    for f in files:
        urllib.urlretrieve(f, matchdir + "/" + os.path.basename(f))
        print(f)
    filepath = os.getcwd() + "/" + matchdir
    os.chdir("code")

    try:
        eng = engine.start_matlab()
        res = eng.LanQi(filepath + "/", 'sensor-R.txt', 'sensor-L.txt', 'angle-R.txt', 'angle-L.txt', 'gps-L.txt',
                        'court-config.txt', 'result-run.txt', 'result-turn.txt', 'result-pass.txt', 'result-step.txt',
                        'result-shoot.txt', nargout=0)
    except:
        res = False
    else:
        res = True

    os.chdir(rootpath)
    # 检查是否执行成功

    if res:
        data = {"code": 200,
                "msg": "计算成功",
                "id": id,
                "pathroot": "http://" + request.host + "/" + matchdir,
                "resPass": "result-pass.txt",
                "resRun": "result-run.txt",
                "resShoot": "result-shoot.txt",
                "resStep": "result-step.txt",
                "resTurn": "result-turn.txt",
                }
    else:
        data = {"code": 2001, "msg": "计算失败", "id": id}

    return data
    # urllib2.urlopen(url=callbackurl,data=urllib.urlencode(data))


@app.route("/court", methods=["POST", 'GET'])
def court():
    """
    """
    rootpath = os.getcwd()
    id = request.form['id']
    client = request.form['client']
    datafile = request.form['datafile']

    mkdir(["static", "court", client, id])
    courtpath = "static/court/" + client + "/" + id
    urllib.urlretrieve(datafile, courtpath + "/" + os.path.basename(datafile))  # 下载文件

    try:
        # 开始计算
        os.chdir(rootpath + "/code")
        eng = engine.start_matlab()
        res = eng.Stadium(rootpath + "/" + courtpath + "/", "border-src.txt", "border-dest.txt", nargout=0)
    except:
        data = {"code": 2001, "msg": "球场计算失败"}
    else:
        data = {"code": 200, "msg": "球场计算成功",
                "datafile": "http://" + request.host + "/" + courtpath + "/border-dest.txt"}

    os.chdir(rootpath)
    return data


@app.route("/compass", methods=["POST", "GET"])
def compass():
    mkdir(["static", "compass"])
    fname = str(random.random())
    compass_ersion = int(request.form['compassVersion'])
    compass_sensor_data = request.form['compassSensorData']
    filepath = "static/compass/" + fname
    md5 = hashlib.md5(compass_sensor_data).hexdigest()

    # md5 校验
    if md5 != request.form['md5']:
        return {"code": 2002, "msg": "md5校验错误"}

    with open(filepath, 'w') as fd:
        fd.write(compass_sensor_data)

    path = os.getcwd()
    infile = path + "/" + filepath
    outfile = infile + ".dest"

    if compass_ersion == 0:
        compass_ersion = ""
    else:
        compass_ersion = str(compass_ersion)

    res = os.system("/usr/bin/compass" + compass_ersion + " " + infile + " " + outfile + " ")
    #
    # if res > 0:
    #     code = 2001
    #     data = ""
    # else:
    #     code = 200
    #     with open(outfile) as f:
    #         data = f.read()
    code = 200
    with open(outfile) as f:
        data = f.read()
    os.remove(infile)
    os.remove(outfile)
    return {"code": code, "data": data}


if __name__ == "__main__":
    app.run(host=config.WEB_HOST, debug=config.WEB_DEBUG, port=config.WEB_PORT)
